<template>
<!--  <div class="enter_wrap">-->
<!--    思考：<p v-html="result"/>-->
<!--    回答：<p v-html="content"/>-->
<!--  </div>-->
  <div class="ai_wrap">
    <div class="title_area">
      <h3 @click="intoAllList">彭州政务智能客服</h3>
      <p>Deepseek助力智能化政务服务</p>
    </div>
    <div class="chat_area">
      <div id="chatContent" class="chat_con" ref="scrollWrap">
        <ul class="content chat_list">
          <li v-for="(item,index) in chatList" :key="'aichat'+index" class="chat_item">
            <div class="ai_info" v-if="item.direction===0">
              <img class="ai_portrait" :src="portrait" />
              <span class="ai_name">{{aiName}}</span>
            </div>
            <div :class="item.direction===0?'ai_msg msg_l':'ai_msg msg_r'" >
              <div class="ai_seek" v-if="item.seek">
                <div class="seek_tit" @click="toggleShowSeek(index)"><span class="seek_txt">思考：</span><van-icon :name="item.showSeek?'arrow-up':'arrow-down'" /></div>
                <span v-if="item.showSeek" v-html="item.seek"></span>
              </div>
              <div class="ai_content">
                <div  class="seek_tit" v-if="item.seek&&item.content">回答：</div>
                <span v-html="item.content"></span>
              </div>
              <div class="hot_business" v-if="index===0">
                <h6 class="t_color3"><img class="fn_type" :src="fnType0" />{{policyTtile}}</h6>
                <ul class="hot_wrap">
                  <li class="hot_item t_color3 l_color3" v-for="(it,ind) in policyData" :key="'policy'+ind" @click="showMorePolicy(it)">{{it}}</li>
                </ul>
              </div>
              <div class="hot_business" v-if="index===0">
                <h6 class="t_color4"><img class="fn_type" :src="fnType4" />{{highTitle}}</h6>
                <ul class="hot_wrap">
                  <li class="hot_item t_color4 l_color4" v-for="(it,ind) in highBusiness" :key="'highBusiness'+ind" @click="sendMsg(it,'high')">{{it}}</li>
                </ul>
              </div>
              <div class="hot_business" v-if="index===0">
                <h6 class="t_color0"><img class="fn_type" :src="fnType1" />{{hotTitle}}</h6>
                <ul class="hot_wrap">
                  <li class="hot_item t_color0 l_color0" v-for="(it,ind) in hotBusiness" :key="'hotBusiness'+ind" @click="sendMsg(it,'que')">{{it}}</li>
                </ul>
              </div>
              <div class="hot_business" v-if="index===0">
                <h6 class="t_color1"><img class="fn_type" :src="fnType2" />{{guideTitle}}</h6>
                <ul class="hot_wrap">
                  <li class="hot_item t_color1 l_color1" v-for="(it,ind) in guideBusiness" :key="'guideBusiness'+ind" @click="sendMsg(it,'gui')">{{it}}</li>
                </ul>
              </div>
              <div class="hot_business" v-if="index===0">
                <h6 class="t_color2"><img class="fn_type" :src="fnType3" />{{aiTitle}}</h6>
                <ul class="hot_wrap">
                  <li class="hot_item t_color2 l_color2" v-for="(it,ind) in aiBusiness" :key="'doBusiness'+ind" @click="intoAiDo(ind,it)">{{it.mattername}}</li>
                </ul>
              </div>
            </div>
            <div class="recommend_wrap" v-if="item.recommend && item.recommend.length>0">
              <p>您可能还需要办理：</p>
              <li class="recommend_item" v-for="(item1,index1) in item.recommend" :key="'recommend'+index1" @click="downloadBlank(item1.url)">{{item1.title}}</li>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div  id="inputContent" class="input_area">
      <div class="chat_input" v-if="canInput">
        <textarea id="inputBox" class="real_input" autofocus :placeholder="canInput?'请输入':''" :disabled="!canInput" v-model="inputText">
        </textarea>
        <div class="send_btn" @click="sendMsg()">
          <svg class="icon" style="width: 2em;height: 2em;fill: #fff;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10587"><path d="M998.976 554.3232C1031.232 539.6032 1031.328 515.7952 998.976 501.0432L122.88 101.3312C90.624 86.6112 64.448 103.5072 64.384 138.4832L64 426.9952 773.568 527.6672 64 628.3392 64.384 916.8832C64.448 952.1152 90.528 968.7872 122.88 954.0352L998.976 554.3232Z" p-id="10588"></path></svg>
        </div>
      </div>
      <div class="seek_loading" v-if="!canInput">
        <svg class="seeking" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5714"><path d="M138 475.6l0.8 0.8L208 407.2l-0.8-0.8c-27.6-27.6-41.2-60.4-41.2-99.6s13.6-72 41.2-99.6S268 166 306.8 166s72 13.6 99.6 41.2l205.2 205.2 69.2-69.2-205.2-205.6C428.8 91.2 372.8 68 306.8 68s-122 23.2-168.8 70C91.2 184.4 68 240.8 68 306.8c0 66 23.2 122 70 168.8z m410.4-337.6l-0.8 0.8L616.8 208l0.8-0.8c27.6-27.6 60.4-41.2 99.6-41.2s72 13.6 99.6 41.2c27.6 27.6 41.2 60.8 41.2 99.6s-13.6 72-41.2 99.6l-205.2 205.2 69.2 69.2 205.6-205.2c46.4-46.4 70-102.8 70-168.8s-23.2-122-70-168.8C839.6 91.2 783.2 68 717.2 68c-65.6 0-122 23.2-168.8 70z m-72.8 748l0.8-0.8-69.2-69.2-0.8 0.8c-27.6 27.6-60.4 41.2-99.6 41.2s-72-13.6-99.6-41.2c-27.6-27.6-41.2-60.8-41.2-99.6s13.6-72 41.2-99.6l205.2-205.2-69.2-69.2-205.6 205.2C91.2 595.2 68 651.2 68 717.2s23.2 122 70 168.8C184.4 932.8 240.8 956 306.8 956c65.6 0 122-23.2 168.8-70z m86.4-323.6c18-18 24.8-44 18.4-68.4s-25.6-43.6-50-50c-24.4-6.4-50.4 0.4-68.4 18.4-27.6 27.6-27.6 72.4 0 100.4 27.6 27.2 72.4 27.2 100-0.4z m324-13.6l-0.8-0.8-69.2 69.2 0.8 0.8c27.6 27.6 41.2 60.4 41.2 99.6s-13.6 72-41.2 99.6c-27.6 27.6-60.8 41.2-99.6 41.2s-72-13.6-99.6-41.2L412.4 612l-69.2 69.2 205.2 205.6c46.4 46.4 102.8 70 168.8 70s122-23.2 168.8-70c46.4-46.4 70-102.8 70-168.8 0-66.4-23.2-122.8-70-169.2z" p-id="5715"></path></svg>
      </div>
    </div>
  </div>
  <van-popup v-model:show="shouldShowPopup" position="bottom" class="more_popup" :style="{ height: '100%' }" close-on-popstate :lock-scroll="false">
    <div class="popup_wrap">
      <div class="list_title content">{{listTitle}}</div>
        <van-search
            v-if="showMoreQuestion || showMoreBusiness"
            v-model="searchValue"
            shape="round"
            placeholder="请输入搜索内容"
            :show-action="true"
            clear-trigger="always"
            action-text="搜索"
        >
          <template #action>
            <div @click="onSearch">搜索</div>
          </template>
        </van-search>
        <Loading v-if="popupLoading"></Loading>
      <div class="more_policy" ref="popupScroll" v-if="showMorePolicyData">
        <ul>
          <li v-for="(item,index) in morePolicy" :key="'pol'+item+index" @click="moreQueHandel(item)">{{item}}</li>
          <p class="is_all" v-if="morePolicy.length>0">--已展示所有政策--</p>
        </ul>
      </div>
        <div class="more_list" ref="popupScroll" v-if="showMoreQuestion">
          <ul>
            <li v-for="(item,index) in moreQuestion" :key="'que'+item.id+index" @click="moreQueHandel(item)">{{item}}</li>
            <p class="is_all" v-if="moreQuestion.length>0">--已展示所有数据--</p>
          </ul>
        </div>
      <div class="more_list" ref="popupScroll" v-if="showMoreBusiness">
        <ul>
          <li v-for="(item,index) in moreBusiness" :key="'high'+item.id+index" @click="moreQueHandel(item.mattername)">{{item.mattername}}</li>
          <p class="is_all" v-if="moreBusiness.length>0">--已展示所有数据--</p>
        </ul>
      </div>
        <div class="guide_list" ref="popupScroll" v-if="showMoreGuide">
          <ul>
          <li class="gui_item" v-for="(item,index) in moreGuide" :key="'que'+item.id+index">
            <h6  @click="showCommunity(item.area,item.id)">{{item.area}}<span style="padding: 0 .1rem;font-weight: 700;font-size: 0.8rem;color: #ff8500;">（村（社区）便民服务站{{item.num}}个）</span></h6>
            <p>电话：<a :href="'tel:'+item.tell">{{item.tell}}</a></p>
            <p  @click="showCommunity(item.area,item.id)">地址：{{item.address}}</p>
          </li>
            <p class="is_all" v-if="moreQuestion.length>0">--已展示所有街道--</p>
          </ul>
        </div>
      <div class="guide_list" ref="popupScroll" v-if="showMoreCommunity">
        <ul>
          <li class="gui_item" v-for="(item,index) in communityData" :key="'que'+item.id+index">
            <h6>{{item.area}}</h6>
            <p>地址：{{item.address}}</p>
          </li>
          <p class="is_all" v-if="communityData.length>0">--已展示所有社区--</p>
        </ul>
      </div>
      <Empty v-if="popupEmpty" emptyNotice="暂无相关内容"></Empty>
    </div>
      <van-icon @click="handleClose" class="popup_close_btn" name="cross" />
      <van-icon v-if="showMoreCommunity" @click="backGuide" class="popup_close_btn back_btn" name="revoke" />
  </van-popup>
</template>

<script>
import BScroll from 'better-scroll'
import axios from "axios";
import Loading from '@/components/Loading'
import Empty from '@/components/Empty'
import Cookies from "js-cookie";
export default {
  name: 'HomeView',
  components: {Loading,Empty},
  data() {
    return {
      flag: true,
      session_id: '',
      old_session_id: '',
      old_session_count: 0,
      result: '',
      content: '',
      aiName:"彭友帮帮妹",
      inputText:"",
      canInput:true,
      scrollObj:null,
      popupScrollObj:null,
      aiTitle:"您可以在线预审办理：",
      highTitle:"您可以查询高频事项办事指南",
      //aiBusiness:["城乡居民基本养老保险参保登记网上预审","《食品经营许可证》核发网上预审"],
      aiBusiness:[],
      portrait:require("../assets/portrait.png"),
      fnType0:require("../assets/fn_type0.png"),
      fnType1:require("../assets/fn_type1.png"),
      fnType2:require("../assets/fn_type2.png"),
      fnType3:require("../assets/fn_type3.png"),
      fnType4:require("../assets/fn_type4.png"),
      hotTitle:"您可以尝试这样问我：",
      guideTitle:"您可以选择对应区域进行引导:",
      guideBusiness:["政务大厅区域引导","企服大厅区域引导","社保退休办理","身份证办理","企业开办","母婴室","..."],
      highBusiness:["合伙企业设立登记","新生儿参保登记","公司设立登记","个体工商户设立登记","社会保障卡启用（激活）","..."],
      policyTtile:"您可以在线査询惠企政策:",
      policyData:["为我推荐彭州市支持服务业发展的政策","为我推荐彭州市支持建筑业发展的政策","为我推荐彭州市支持制造业发展的政策","为我推荐彭州市支持中医药产业发展的政策","为我推荐彭州市人才惠企政策"],
      //hotBusiness:["职工参保登记(灵活就业人员参保登记)","养老保险定期待遇领取资格认证","存量房买卖合同网签备案","《食品经营许可证》核发","新生儿入户","城乡居民基本养老保险参保登记","大厅免费WIFI","..."],
      hotBusiness:["彭州市政务服务中心在哪里？","彭州市企业服务中心在哪里？","身份证是否可以在网上办理吗？","我市公租房点位有哪些吗？","政务大厅免费WIFI","..."],
      chatList:[
        {direction:0,seek:"",content:"您好，我是“彭友帮帮妹”Ai政务小助手，我通晓彭州市政务相关的服务信息，希望我的服务为您提供良好的智能政务体验！"}
      ],
      showMoreQuestion:false,
      showMoreBusiness:false,
      showMoreGuide:false,
      showMoreCommunity:false,
      showMorePolicyData:false,
      moreQuestion:[],
      moreBusiness:[],
      moreAllQuestion:[],
      moreAllBusiness:[],
      moreGuide:[],
      morePolicy:[],
      popupLoading:false,
      popupEmpty:false,
      searchValue:'',
      communityData:[],
      listTitle:'',
    }
  },
  created() {
    this.intoVist()
    this.findSPMatter()
    if(this.$route.query.type == 'cjwt'){
      this.sendMsg('...','que')
    }

  },
  setup() {

  },
  computed: {
    shouldShowPopup() {
      return this.showMoreQuestion || this.showMoreGuide || this.showMoreCommunity || this.showMorePolicyData || this.showMoreBusiness;
    }
  },
  methods: {
    toggleShowSeek(i){
      this.chatList[i].showSeek=!this.chatList[i].showSeek
      this.scrollObj.refresh()
      this.$nextTick(() => {
        this.scrollObj.refresh()
      })
    },
    showMorePolicy(policy){
      this.showMorePolicyData = true
      this.listTitle = policy
          this.popupLoading = true
      const url = `https://www.pengzhou.org.cn/api/znsp/findZcwjList?institution=${policy}`
      axios.get(url,{},{headers: {'Content-Type': 'multipart/form-data'}}).then(response => {
        if (response.data && response.data.success) {
          this.morePolicy = response.data.data
          this.popupLoading = false
          this.$nextTick(() => {
            this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
              click: true,
            })
          })
          this.popupEmpty = response.data.data.length===0
        }}).catch(error => {
        console.error('Error:', error);
      });
    },
    handelUrl(url){
      window.location.href = url
    },
    backGuide(){
      this.showMoreCommunity = false
      this.showMoreGuide = true
      this.displayMoreGuide()
      this.getListTit()
    },
    getListTit(name){
      if(name){
        this.listTitle = name.slice(0, -6)
      }else if (this.showMoreBusiness) {
        this.listTitle = "高频事项"
      }else if (this.showMoreQuestion) {
        this.listTitle = "常见问题"
      } else if (this.showMoreGuide) {
        this.listTitle = "点位引导"
      } else {
        this.listTitle = ''
      }
    },
    showCommunity(name,id){
      this.getListTit(name)
      this.communityData = []
      this.showMoreCommunity = true
      this.showMoreGuide = false
      this.popupLoading = true
      this.popupScrollObj = null
      const url = `https://www.pengzhou.org.cn/api/znsp/areaListSQ?id=${id}`;
      axios.get(url,{},{
        headers: {
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }}).then(response => {
        if (response.data && response.data.success) {
          this.communityData = response.data.data
          this.popupLoading = false
          this.$nextTick(() => {
            this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
              click: true,
            })
          })
          this.popupEmpty = response.data.data.length===0
        }}).catch(error => {
        console.error('Error:', error);
      });
    },
    onSearch(){
      this.moreQuestion =[]
      this.moreBusiness = []
      if(this.searchValue==""){
        if(this.showMoreQuestion){
          this.moreQuestion = this.moreAllQuestion
        }
        if(this.showMoreBusiness){
          this.moreBusiness = this.moreAllBusiness
        }
        this.popupEmpty = false
        this.$nextTick(() => {
          this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
            click: true,
          })
        })
      }else{
        if(this.showMoreQuestion){
          this.displayMoreQuestion()
        }
        if(this.showMoreBusiness){
          this.displayMoreBusiness()
        }
      }
    },
    getResultResponse(obj) {
      let datas = obj.split('event:result')
      let pattern_response = /"response"\s*:\s*"([^"]*)"/;
      let buff = ''
      for(let i=1;i<datas.length;i++){
        let match_response = datas[i].match(pattern_response);
        if(match_response){
          buff+=match_response[1]
        }
      }
      return buff;
    },
    getResultText(obj) {
      let datas = obj.split('event:result')
      let pattern_text = /"text"\s*:\s*"([^"]*)"/;
      let buff = ''
      for(let i=1;i<datas.length;i++){
        let match_text = datas[i].match(pattern_text);
        if(match_text){
          buff+=match_text[1]
        }
      }
      return buff;
    },
    intoVist(){
      const url = `https://www.pengzhou.org.cn/api/znsp/intoYYKFVist`;
      try {
        fetch(url, {
          method: 'GET',
        }).then(async response =>  {})
      } catch (error) {
      }
    },
    intoCount(){
      const url = `https://www.pengzhou.org.cn/api/znsp/intoYYKFCount`;
      try {
        fetch(url, {
          method: 'GET',
        }).then(async response =>  {})
      } catch (error) {
      }
    },
    findSPMatter(){
      const url = `https://www.pengzhou.org.cn/api/znsp/findSPMatter`;
      axios.get(url,{},{
        headers: {
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }}).then(response => {
        if (response.data && response.data.success) {
          this.aiBusiness = response.data.data
          this.$nextTick(() => {
            this.scrollObj = new BScroll(this.$refs.scrollWrap, {
              click: true,
            })
          })
        }}).catch(error => {
        console.error('Error:', error);
      });
    },

    displayMoreBusiness(){
      this.showMoreBusiness = true
      if(this.moreBusiness.length == 0){
        this.popupLoading = true
        //const url = `https://www.pengzhou.org.cn/api/znsp/findQueList?name=${this.searchValue}`;
        const url = `https://www.pengzhou.org.cn/api/znsp/matterList?name=${this.searchValue}`;
        axios.get(url, {}, {
          headers: {
            'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
          }
        }).then(response => {
          if (response.data && response.data.success) {
            this.moreBusiness = response.data.data
            this.popupLoading = false
            if(this.searchValue==""){
              this.moreAllBusiness = response.data.data
            }
            this.$nextTick(() => {
              this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
                click: true,
              })
            })
            this.popupEmpty = response.data.data.length===0
          } else {
            this.popupLoading = false
          }
        }).catch(error => {
          this.popupLoading = false
          console.error('Error:', error);
        });
      }else{
        this.$nextTick(() => {
          this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
            click: true,
          })
        })
      }
    },
    displayMoreQuestion(){
      this.showMoreQuestion = true
      if(this.moreQuestion.length == 0){
        this.popupLoading = true
        const url = `https://www.pengzhou.org.cn/api/znsp/findQueList?name=${this.searchValue}`;
        axios.get(url, {}, {
          headers: {
            'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
          }
        }).then(response => {
          if (response.data && response.data.success) {
            this.moreQuestion = response.data.data
            this.popupLoading = false
            if(this.searchValue==""){
              this.moreAllQuestion = response.data.data
            }
            this.$nextTick(() => {
              this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
                click: true,
              })
            })
            this.popupEmpty = response.data.data.length===0
          } else {
            this.popupLoading = false
          }
        }).catch(error => {
          this.popupLoading = false
          console.error('Error:', error);
        });
      }else{
        this.$nextTick(() => {
          this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
            click: true,
          })
        })
      }
    },
    displayMoreGuide(){
      this.showMoreGuide = true
      if(this.moreGuide.length == 0){
        this.popupLoading = true
        const url = `https://www.pengzhou.org.cn/api/znsp/areaList`;
        axios.get(url, {}, {
          headers: {
            'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
          }
        }).then(response => {
          if (response.data && response.data.success) {
            this.moreGuide = response.data.data
            this.popupLoading = false
            this.$nextTick(() => {
              this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
                click: true,
              })
            })
          } else {
            this.popupLoading = false
          }
        }).catch(error => {
          this.popupLoading = false
          console.error('Error:', error);
        });
      }else{
        this.$nextTick(() => {
          this.popupScrollObj = new BScroll(this.$refs.popupScroll, {
            click: true,
          })
        })
      }
    },
    handleClose() {
      this.showMoreQuestion = false;
      this.showMoreBusiness = false;
      this.showMoreGuide = false;
      this.showMoreCommunity = false;
      this.showMorePolicyData = false;
      this.searchValue = ""
      this.popupEmpty =false
      this.popupLoading = false
      this.moreQuestion = []
      this.moreBusiness = []
    },
    moreQueHandel(item){
      this.handleClose()
      this.sendMsg(item)
    },
    moreGuiHandel(item){
      this.handleClose()
      this.sendMsg(item.area)
    },
    //文件下载
    downloadBlank(url){
      this.$router.push({
        path: '/download',
        query: {
          url: url,
        }
      })
    },
    //20250713测试数据
    intoAllList() {
      this.$router.push({
        path: '/allBusinessList',
      })
    },
    setRandomData(obj) {
      //提交数据
      //console.log(decodeURIComponent(JSON.stringify(this.newUploadObj)))
      const url = "https://www.pengzhou.org.cn/api/znsp/findZcwj";
      axios.post(url,{
        content:obj.content
      },{
        headers: {
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }
      }).then(response => {
        if (response.data.data) {
          obj.recommend = [{title:'政策文件下载',url:response.data.data}]
          this.$nextTick(() => {
            this.scrollObj.refresh()
            this.scrollObj.scrollTo(0, this.scrollObj.maxScrollY);
          })
        }else{
          obj.recommend = []
        }}).catch(error => {
        console.error('Error:', error);
      });

    },
    sendMsg(msg,type){
      if(msg == '...' && type=='que'){
        this.displayMoreQuestion()
        this.popupScrollObj = null
        this.getListTit()
        return
      }
      if(msg == '...' && type=='gui'){
        this.displayMoreGuide()
        this.popupScrollObj = null
        this.getListTit()
        //更多指引
        return
      }
      if(msg == '...' && type=='high'){
        this.displayMoreBusiness()
        this.popupScrollObj = null
        this.getListTit()
        return
      }
      if(!this.canInput)return
      this.chatList.push({
        direction:1,
        seek:"",
        content: msg || this.inputText
      })
      this.fetchData(msg || this.inputText)
      this.$nextTick(() => {
        this.scrollObj.refresh()
        this.scrollObj.scrollTo(0, this.scrollObj.maxScrollY);
        this.inputText = ""
        this.canInput = false
      })
    },
    intoAiDo(index,it){
      const url = `https://www.pengzhou.org.cn/api/sys/user/checkusers`;
      axios.get(url,{},{
        headers: {
          'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
        }}).then(response => {
        if (response.data && response.data.data) {
          this.$router.push({
            path: '/aiBusiness1',
            query: {
              id: it.id,
              mattername: it.mattername
            }
          })
        }else{
          let toUrl = aiBusiness + '?id='+it.id
          window.location.replace(systemUrl + '?wxurl=' + encodeURI(toUrl))
          index = index+1
        }}).catch(error => {
          console.error('Error:', error);
          let toUrl = aiBusiness + '?id='+it.id
          window.location.replace(systemUrl + '?wxurl=' + encodeURI(toUrl))
          index = index+1
      });
    },
      async fetchData(obj) {
          this.intoCount()
          if(this.old_session_count >=2){
            this.session_id = ''
            this.old_session_count = 0
            this.old_session_id = ''
          }
          // 若没有配置环境变量，可用百炼API Key将下行替换为：apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
          const apiKey = 'sk-52886024a70d41349a9cc76c654a8bb8';
          const appId = 'fd90f82c8d4b40d8a350390648a03052';// 替换为实际的应用 ID
          const data = {
              input: {
                  prompt: obj,
                  session_id: this.session_id
              },
              parameters: {
                  'has_thoughts' : 'true', //是否大脑思考
                  'incremental_output' : 'true' // 增量输出
              },
              debug: {}
          };
          const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
          try {
              fetch(url, {
                  responseType: 'stream',
                  method: 'POST', // 或 'PUT' 等，取决于你的需求
                  headers: {
                      'Authorization': `Bearer ${apiKey}`,
                      'Content-Type': 'application/json',
                      'X-DashScope-SSE': 'enable' // 流式输出
                  },
                  body: JSON.stringify(data) // 将JavaScript对象转换为JSON字符串
              }).then(async response =>  {
                  this.chatList.push({
                    direction:0,
                    showSeek:true,
                    seek:"",
                    content: ""
                  })
                  const msgIndex = this.chatList.length-1
                  const reader = response.body.getReader();
                  const decoder = new TextDecoder('utf-8');
                  let list = []
                  this.session_id = ''
                  while (this.flag) {
                    const { done, value } = await reader.read();
                    if (done) {
                      this.canInput = true
                      list = []
                      this.setRandomData(this.chatList[msgIndex])
                      break
                    };
                    list.push(decoder.decode(value, { stream: true }))
                    this.flag = false
                    // 定义正则表达式来匹配 chunk_message 的值，我们只要chunk_message对应的值
                    //因为json数据和text/event-stream数据不同，json数据可以通过.访问chunk_message 的值，
                    //但是text/event-stream数据是个纯文本，不能通过.访问chunk_message，我们用正则表达式来获取需要的数据
                    // 使用正则表达式进行匹配 获取多话session_id
                    if(this.session_id == ''){
                      let pattern_session = /"session_id"\s*:\s*"([^"]*)"/;
                      let match_session = list[0].match(pattern_session);
                      if(match_session){
                        this.session_id = match_session[1]
                        if(this.old_session_id == ''){
                          this.old_session_id = this.session_id;
                        }else if(this.old_session_id == this.session_id){
                          this.old_session_count+=1
                        }
                      }
                    }

                    //获取思考过程
                    let responseResult = this.getResultResponse(list[0])
                    if (responseResult) {
                      // 提取匹配到的值
                      this.chatList[msgIndex].seek += responseResult.replace(/\\n/g, '<br>')
                      this.scrollObj.refresh()
                      this.scrollObj.scrollTo(0, this.scrollObj.maxScrollY);
                    }
                    //获取回答值
                    let responseText = this.getResultText(list[0])
                    if (responseText) {
                      this.chatList[msgIndex].showSeek = false
                      // 提取匹配到的值
                      this.chatList[msgIndex].content += responseText.replace(/\\n/g, '<br>').replaceAll(/\*/g, '').replaceAll(/\#/g, '')
                      this.scrollObj.refresh()
                      this.scrollObj.scrollTo(0, this.scrollObj.maxScrollY);
                    }
                    list.shift()
                    this.flag = true
                  }
              })
          } catch (error) {
              console.error('请求失败:', error);
          }
      }
  }
}
</script>

<style scoped>
.ai_wrap {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: url("../assets/pz_bgtop0.jpg") #f8f8f8 top center no-repeat;
  background-size: contain;
  text-align: left;
}


.title_area {
  width: 90%;
  height: 14vh;
  overflow: hidden;
  margin: 25px 20px -25px;
  color: #fff;
}

.title_area h3 {
  font-size: 18px;
  font-weight: bold;
}

.title_area p {
  font-size: 14px;
  margin-top: 6px;
}
.chat_area{
  width:100%;
  height:75vh;
}
.input_area{
  width:100%;
  height:10vh;
}
.chat_con{
  width:90%;
  height:97%;
  border:solid 2px #e8e8e8;
  margin: 0 auto;
  overflow: hidden;
  background:#f8f8f8;
  border-radius: 1em;
}
.chat_list{
  padding:0.6rem;
}
.chat_item{
  overflow: hidden;
}
.chat_input{
  width:90%;
  height:80%;
  position: relative;
  overflow: hidden;
  border:solid 2px #78a1e1;
  margin: 0 auto;
  background: #e8e8e8;
  border-radius: 1em;
}
.real_input{
  width:75%;
  height:90%;
  margin: 5px;
  box-sizing: border-box;
  border: none;
  font-size: 16px;
  background: none;
  position: absolute;
  left:0;
  top:0;
  overflow: hidden;
}
.send_btn{
  width:25%;
  height:101%;
  background: #78a1e1;
  position: absolute;
  right:0;
  top:0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.ai_info{
  width:100%;
  display: flex;
  float:left;
  margin-top: 0.5rem;
  align-items: center;
}
.ai_portrait{
  width:35px;
  height:35px;
  margin-right: 0.5rem;
}
.ai_name{
  color: #5482eb
}
.seek_tit{
  display: flex;
  color: #5482eb;
  font-weight: bold;
}
.seek_txt{
  flex:1
}
.ai_msg{
  max-width: 96%;
  position: relative;
  margin-top:0.5rem;
  padding:0.5rem;
}
.ai_msg span{
  word-wrap: break-word;
}
.msg_l{
  float:left;
  background: #ecebeb;
  color:#363636;
  margin_bottom:0.8rem;
  border-radius: 0 0.6rem 0.6rem 0.6rem;
}
.msg_r{
  float:right;
  background:#5482eb;
  color:#ffffff;
  margin_bottom:1rem;
  border-radius: 0.6rem 0.6rem 0 0.6rem;
}
.ai_seek{
  color: #9f9c9c;
  padding-bottom: 0.3rem;
  border-bottom: solid 1px #e1e1e1;
}
.ai_content{
  padding-top: 0.3rem;
}
.seek_loading{
  width:90%;
  height:80%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border:solid 2px #78a1e1;
  margin: 0 auto;
  background: #a3c0ee;
  border-radius: 1em;
}
.seeking{
  fill:#fff;
  width:1.9rem;
  height:1.9rem;
  opacity: 0.4;
  animation: rotate 1s ease-in-out infinite;
}
.hot_business{
  width:100%;
  margin-top: 0.5rem;
}
.hot_business h6{
  font-size: 12px;
  display: flex;
  align-items: center;
  margin: 12px 0 8px;
}
.fn_type{
  width:26px;
  height:26px;
  margin-right: 5px;
}
.t_color0{
  color:#ef820a;
}
.t_color1{
  color:#2ab672;
}
.t_color2{
  color: #4c74d0;
}
.t_color3{
  color:#984bb2;
}
.t_color4{
  color: #d75b5b;
}
.l_color0{
  background: #f3eadf;
}
.l_color1{
  background: #dbf1e5;
}
.l_color2{
  background: #f3e4e4;
}
.l_color3{
  background: #e1d1e7;
}
.l_color4{
  background: #ffe0e0;
}
.hot_item{
  display: inline-block;
  padding:0.3rem 0.5rem;
  margin:0.3rem 0.2rem;
  font-size: 12px;
  background: #f6f6f6;
  border-radius: 0.3rem;
}
.more_popup{
  text-align: left;
  overflow: hidden;
  overflow-x: hidden!important;
}
.list_title{
  height:50px;
  line-height: 30px;
  padding:20px;
  box-sizing: border-box;
  font-size: 16px;
  color: #4c74d0;
  text-align: left;
  font-weight: bold;
}
.list_wrap{
  width: 100%;
  padding:12px 0;
}
.more_list li, .guide_list li, .more_policy li{
  width:85%;
  padding:10px 15px;
  margin:12px auto;
  background: #f8f8f8;
  text-align: left;
  border-radius: 10px;
  box-shadow: 1px 1px 3px #cbcbcb;
}
.gui_item h6{
  padding: 6px 0;
  font-size: 14px;
  font-weight: bold;
  border-bottom: dotted 1px #dadada;
  margin-bottom: 4px;
}
.gui_item p{
  padding: 2px 0;
}
.gui_item a{
  color:#4c74d0
}
.popup_close_btn{
  position: fixed;
  top:18px;
  right:18px;
  font-size: 20px;
}
.back_btn{
  font-size: 18px;
  right:48px;
  font-weight: bold;
}
.popup_close_btn:before {

  color:#acacac;
  display: inline-block;
}
.more_list{
  width:100%;
  height:100%;
  margin-top: 110px;
  box-sizing: border-box;
  position: absolute;
  top:0;
  overflow: hidden;
}
.more_list ul{
  padding-bottom: 110px;
}
.more_policy{
  width:100%;
  height:100%;
  margin-top: 60px;
  box-sizing: border-box;
  position: absolute;
  top:0;
  overflow: hidden;
}
.more_policy ul{
  padding-bottom: 60px;
}
.guide_list{
  width:100%;
  height:100%;
  margin-top: 60px;
  box-sizing: border-box;
  position: absolute;
  top:0;
  overflow: hidden;
}
.guide_list ul{
  padding-bottom: 60px;
}
.popup_wrap{
  width:100%;
  height:100%;
  position: relative;
  overflow: hidden;
}
.is_all{
  font-size: 12px;
  color: #605b5b;
  padding:10px 0;
}
.popup_con{
  height:auto;
}
.recommend_wrap{
  width:100%;
  clear:both;
  padding-top: 12px;
}
.recommend_wrap p{
  font-size:12px;
  color:#9f9c9c;
}
.recommend_item{
  display: inline-block;
  color:#4c74d0;
  font-size: 14px;
  line-height: 24px;
  padding:1px 5px;
  border:solid 1px #4c74d0;
  border-radius: 6px;
  margin-right: 8px;
  margin-top: 5px;
}
/deep/ .van-search__content{
  background: #f1efef;
}
/deep/ .van-search__action{
  width: 20%;
  height: 100%;
  background-color: #4c74d0;
  color:#fff;
  display: flex;
  border-radius: 1.3em;
  margin:0 10px;
  justify-content: center;
  align-items: center;
}
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
